package es.juanc.threads.sync5;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Cuenta {

	public final Lock monitor = new ReentrantLock();

	private String code;
	private int saldo;

	public Cuenta(String code, int saldoInicial) {
		this.code = code;
		saldo = saldoInicial;
	}

	public boolean deposita(int monto) throws InterruptedException {
		if (monitor.tryLock(1, TimeUnit.SECONDS)) {
			try {
				saldo += monto;
				return true;
			} finally {
				monitor.unlock();
			}
		}
		return false;
	}

	public boolean retira(int monto) throws InterruptedException {
		if (monitor.tryLock(1, TimeUnit.SECONDS)) {
			try {
				saldo -= monto;
				return true;
			} finally {
				monitor.unlock();
			}
		}
		return false;
	}

	public int getSaldo() throws InterruptedException {
		if (monitor.tryLock(1, TimeUnit.SECONDS)) {
			try {
				return saldo;
			} finally {
				monitor.unlock();
			}
		}
		throw new IllegalStateException("No puedo consultar saldo");
	}

	public String getCode() {
		return code;
	}

	@Override
	public String toString() {
		return "Cuenta [code=" + code + ", saldo=" + saldo + "]";
	}
}